import puppeteer from "puppeteer";
import { fmtCookie, delay } from "./utils/utils.js";
/**
 * 掘金
 */
class Juejin {
  COOKIE = `_ga=GA1.2.1175650538.1625016068; _gid=GA1.2.1806146530.1625016068; passport_csrf_token_default=89994c2393a009028aaff5f988b469cb; passport_csrf_token=89994c2393a009028aaff5f988b469cb; passport_auth_status=3c605523d3e2d80a6b3988deb78a8005,; passport_auth_status_ss=3c605523d3e2d80a6b3988deb78a8005,; sid_guard=b2bae74bb1edf36d919a5e02a0e276db|1625037360|5184000|Sun,+29-Aug-2021+07:16:00+GMT; uid_tt=bca020ebcfc3c6eb3b8767176a44eff5; uid_tt_ss=bca020ebcfc3c6eb3b8767176a44eff5; sid_tt=b2bae74bb1edf36d919a5e02a0e276db; sessionid=b2bae74bb1edf36d919a5e02a0e276db; sessionid_ss=b2bae74bb1edf36d919a5e02a0e276db; n_mh=Sm2t33rxNzBvGnt4_MrMX58KYacNoVNbssiDTW9T7Xs; MONITOR_WEB_ID=f0d546da-8883-4157-befb-b4c75a73fc68`;
  browser;
  page;
  constructor() {
    this.init();
  }

  // 设置cookie
  async addCookies(cookies_str, domain) {
    let cookies = fmtCookie(cookies_str, domain);
    await Promise.all(
      cookies.map((pair) => {
        return this.page.setCookie(pair);
      })
    );
  }

  async init() {
    this.browser = await puppeteer.launch({
      headless: true,
      args: ["--no-sandbox"],
      defaultViewport: {
        width: 1800,
        height: 1200,
      },
    });
    this.page = await this.browser.newPage();
    await this.page.setUserAgent(
      "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
    );
    await this.addCookies(this.COOKIE, ".juejin.cn");
    // this.main();
  }
  // 查看当前屏幕实时截图
  getScreenshot() {
    this.page.screenshot({ path: "juejin.png" });
  }

  async main() {
    await this.page.goto("https://juejin.cn/pins/recommended");
    const btn = await this.page.$(".add-btn");
    await btn.click();
    const input = await this.page.$(".auth-card");
    await input.click();
    await this.page.keyboard.type("Hello World!");
    await delay(500);
    // const submit = await this.page.$(".submit");
    // console.log("submit", submit);
    fetch("https://api.juejin.cn/content_api/v1/short_msg/publish", {
      headers: {},
    });
    await delay(500);
    await submit.tap();
    this.getScreenshot();
  }
}

(async () => {
  const juejin = new Juejin();
  await delay(500);
  juejin.main();
})();
